<template>
    <div>
        <div class="cameraBox">
            <video id="videoCamera" class="videoCamera" :width="videoWidth" :height="videoHeight"></video>
            <canvas id="canvasCamera" class="canvasCamera" :width="videoWidth" :height="videoHeight">
            </canvas>
            <div>
                <el-button @click="photograph">拍照</el-button>
                <el-button v-if="flag" @click="openCamera">打开摄像头</el-button>
                <el-button v-else @click="closeCamera">关闭摄像头</el-button>
                <el-button @click="resetPhoto">重置</el-button>
                <el-button @click="goStuInfoEntry">提交</el-button>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            flag: false,
            videoWidth: 500,
            videoHeight: 350,
            thisVideo: null,
            thisContext: null,
            thisCanvas: null,
            imgSrc: "",
        };
    },
    mounted() {
        this.openCamera();
    },
    methods: {
        // 重置
        resetPhoto() {
            this.thisCanvas = document.querySelector(".canvasCamera");
            this.thisContext = this.thisCanvas.getContext("2d");
            this.thisContext.clearRect(0, 0, this.videoWidth, this.videoHeight);
        },
        goStuInfoEntry() {
            //将this.imgSrc传递给学生信息录入组件  跳转到学生信息录入
            console.log(this.imgSrc);
            this.$router.push({
                name: "stuInfoEntry",
                query: {
                    imgSrc: this.imgSrc,
                },
            });
        },
        photograph() {
            // 拍照  使用canvas画布
            this.thisCanvas = document.querySelector(".canvasCamera");
            this.thisContext = this.thisCanvas.getContext("2d");
            //视频    图像起始坐标    结束坐标
            this.thisContext.drawImage(this.thisVideo, 0, 0, 240, 200);
            //参数一：图片的类型  参数二：图片的质量 0-1，默认为0.92，超出范围为默认值

            this.imgSrc = this.thisCanvas.toDataURL("image/png", 0.1);
        },
        // 打开本地摄像头
        openCamera() {
            this.flag = false;
            // 获取video
            this.thisVideo = document.getElementById("videoCamera");
            // 打开本地摄像头 navigator.mediaDevices.getUserMedia
            // 旧版本浏览器 可能不支持mediaDevices ，将navigator.mediaDevices设计为一个空对象
            if (navigator.mediaDevices === undefined) {
                navigator.mediaDevices = {};
            }
            // 有些浏览器 getUserMedia 有的某些浏览器它会覆盖该属性
            if (navigator.mediaDevices.getUserMedia === undefined) {
                navigator.mediaDevices.getUserMedia = function (constraints) {
                    //兼容处理   获取不同浏览器的getUserMedia
                    let getUserMedia =
                        navigator.webkitGetUserMedia ||
                        navigator.mozGetUserMedia ||
                        navigator.getUserMedia;
                    //如果没有
                    if (!getUserMedia) {
                        return Promise.reject(new Error("请更换浏览器"));
                    }
                    // 如果有getUserMedia  （在不同内核有） 将其给navigator
                    return new Promise((resolve, reject) => {
                        getUserMedia.call(navigator, constraints, resolve, reject);
                    });
                };
            }
            // constraints 传入音频视频文件信息
            const constraints = {
                audio: false,
                video: {
                    width: this.videoWidth,
                    height: this.videoHeight,
                },
            };
            // 调用摄像头
            navigator.mediaDevices
                .getUserMedia(constraints)
                .then((res) => {
                    // res 实时数据流
                    console.log(res);
                    // video当中是否有srcObject属性如果有 ，将实时数据流放到该函数内
                    console.log(this.thisVideo);
                    if ("srcObject" in this.thisVideo) {
                        this.thisVideo.srcObject = res;
                    } else {
                        // window.URL.createObjectURL 创建一个新的对象 URL
                        this.thisVideo.src = window.URL.createObjectURL(res);
                    }
                    //onloadedmetadata 视频数据加载完毕后触发
                    this.thisVideo.onloadedmetadata = function () {
                        console.log("视频元数据加载完毕");
                        console.log(this);
                        this.play();
                    };
                })
                .catch((err) => {
                    console.log(err);
                    this.$message({
                        message: "没有开启摄像头或者浏览器不支持请求更换浏览器",
                        type: "warning",
                    });
                });
        },
        // 关闭摄像头
        closeCamera() {
            if (this.thisVideo && this.thisVideo !== null) {
                this.thisVideo.srcObject.getTracks()[0].stop();
                this.flag = true;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
div {
    .videoCamera {
        margin-right: 10px;
    }
}
</style>